<?php
namespace Admin\Controller;

use Think\Page;

class GroupController extends CommonController
{
    public $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = M('admin_group');
    }

    /**
     * 数据列表
     * @return [type]
     */
    public function index()
    {
        $where = [];

        $count = $this->model->where($where)->count();
        $this->assign('count', $count);

        $pages = new Page($count, C('PAGE'), $fields);
        $this->assign('pages', $pages->show());

        $datas = $this->model->where($where)->limit($pages->firstRow . ',' . $pages->listRows)->select();
        $this->assign('datas', $datas);

        $this->assign('bread_crumb', $bread_crumb = generate_bread_crumb([
            '权限控制',
            '角色列表',
        ]));
        $this->display();
    }

    /**
     * 添加数据，添加完修改
     */
    public function add()
    {
        if (IS_GET) {

            $this->assign('rules', $rules = D('rule')->getRules());

            $this->display();

        } elseif (IS_POST) {

            $data  = I('post.m', []);
            $rules = I('post.rules', []);
            if (!$rules) {
                $this->error('请选择一个权限');
            }

            $data['rules'] = implode(',', $rules);

            $id = $this->model->add($data);

            if ($id) {
                $this->success('添加成功', U(CONTROLLER_NAME . '/update', [
                    'id' => $id,
                ]));
            }
        }
    }

    public function update()
    {
        if (IS_GET) {

            $id = I('get.id', 0, 'intval');

            $data          = $this->model->find($id);
            $data['rules'] = explode(',', $data['rules']);
            $this->assign('data', $data);

            $this->assign('rules', $rules = D('rule')->getRules());

            $this->display();

        } elseif (IS_POST) {

            $id   = I('post.id', 0, 'intval');
            $data = I('post.m', []);

            $rules = I('post.rules', []);
            if (!$rules) {
                $this->error('请选择一个权限');
            }

            $data['rules'] = implode(',', $rules);
            $this->model->where(['id' => $id])->save($data);

            $this->success('修改成功', U(CONTROLLER_NAME . '/update', [
                'id' => $id,
            ]));
        }
    }
}
